package io.shallwe.scanner.auto;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

import org.apache.commons.lang3.StringUtils;
import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.TioConfig;
import org.tio.core.intf.Packet;

import com.jfinal.aop.Aop;
import com.jfinal.kit.LogKit;

import io.shallwe._admin.line.EnterScanService;
import io.shallwe._admin.line.ExitScanService;
import io.shallwe.scanner.manual.MessagePacket;

public class AutoScannerClientHanlder implements ClientAioHandler {
	EnterScanService enterScanService = Aop.get(EnterScanService.class);
	ExitScanService exitScanService = Aop.get(ExitScanService.class);

	@Override
	public Packet decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext){
		if (readableLength < 3) {
			return null;
		}
		MessagePacket imPacket = new MessagePacket();
		byte[] body = new byte[readableLength];
		buffer.get(body);
		imPacket.setBody(body);
		return imPacket;
	}

	@Override
	public ByteBuffer encode(Packet packet, TioConfig config, ChannelContext channelContext) {
		MessagePacket helloPacket = (MessagePacket) packet;
		byte[] body = helloPacket.getBody();
		ByteBuffer buffer = ByteBuffer.allocate(body.length);
		buffer.order(config.getByteOrder());
		if (body != null) {
			buffer.put(body);
		}
		return buffer;
	}

	@Override
	public void handler(Packet packet, ChannelContext channelContext) throws Exception {
		String ip = channelContext.getServerNode().getIp();
		MessagePacket helloPacket = (MessagePacket) packet;
		byte[] body = helloPacket.getBody();
		if (body == null) {
			return;
		}
		String code = new String(body, Charset.forName("UTF8"));
		LogKit.error(String.format("收到自动扫描枪:%s的数据:%s", ip, code));
		code = StringUtils.remove(code, (char) 0x1B);
		code = StringUtils.remove(code, (char) 0x20);
		code = StringUtils.remove(code, (char) 0x0D);
		code = StringUtils.remove(code, (char) 0x02);
		code = StringUtils.remove(code, (char) 0x03);
		code = StringUtils.remove(code, (char) 0x04);
		if (StringUtils.startsWith(code, "R")) {
			if (StringUtils.equals("172.30.31.52", ip)) {
				enterScanService.autoScan(code);
			}

			if (StringUtils.equals("172.30.31.53", ip)) {
				exitScanService.autoScan(code);
			}
		}

	}

	@Override
	public Packet heartbeatPacket(ChannelContext channelContext) {
		return null;
	}

}
